<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\api;

use app\common\controller\ApiController;
use app\common\model\Aes;
use think\App;
use app\mill\model\Give as GiveModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Address as AddressModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 用户公开控制器
 * @package app\user\admin
 */
class Index extends ApiController
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $this->is_member();
    }

    /**
     * 监听
     */
    public function timer(){

        success('');
    }
    /**
     * 产品详情
     */
    public function detail(){
        // 获取参数
        $data = input('');

        $where[] = ['give_sn','=',$data['give_sn']];

        $give = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("a.*,o.batch,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($where)
            ->find();

        if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
        $give['status_str'] = GiveModel::$give_status[$give['give_status']];

        success('操作成功',$give);
    }
    /**
     * 扫码更新产品进度
     * @return mixed
     */
    public function ableGive()
    {

        $role = GiveModel::$role;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $_log_time = time();
            $_log_i = 0;
            //file_put_contents('扫码.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

            //获取离线状态下的用户ID
            $archives_sn = !empty($data['archives_sn'])?$data['archives_sn']:'';
            $give_sn = explode(',',$data['give_sn']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';
            $car_ids = !empty($data['car_id'])?explode(',',$data['car_id']):'';
            $color_s = !empty($data['color'])?explode(',',$data['color']):'';
            $address_sn_s = !empty($data['address_sn'])?explode(',',$data['address_sn']):'';

            $user = $this->member;

            $data_list = [];
            if(!empty($give_sn)){
                $_log_str = '';
                foreach ($give_sn as $k=>$v){

                    $uid = !empty($user_ids[$k])?$user_ids[$k]:$user['uid'];
                    $car_id = !empty($car_ids[$k])?$car_ids[$k]:$car_ids;
                    $color = !empty($color_s[$k])?$color_s[$k]:$color_s;
                    $address_sn = !empty($address_sn_s[$k])?$address_sn_s[$k]:$address_sn_s;
                    $user = Db::name('admin_user')
                        ->alias('u')
                        ->field('u.*,u.id as uid,g.name as group_name')
                        ->leftJoin('admin_user_group g','g.id=u.group')
                        ->where(['u.id'=>$uid])
                        ->find();

                    $where = [
                        ['g.give_sn','=',$v],
                    ];

                    //判断产品编号是否完整
                    if(strpos($v,'-') === false){

                        //匹配批次
                        if(!empty($archives_sn)){
                            $where = [
                                ['g.give_sn','like',"%-{$v}"],
                                ['g.archives_sn','=',$archives_sn],
                            ];
                        }
                        else {
                            $where = '1=2';
                            $msg = '请选择批次';
                        }
                    }

                    $give = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field('g.*,g.status as give_status,o.status as order_status,o.is_process')
                        ->leftJoin('mill_order o','o.id=g.order_id')
                        ->where($where)
                        ->find();

                    if($give && $give['order_status'] > 0){
                        $time = time();
                        $status_flow = $give['status_flow'];
                        $group = $user['group'];
                        //补扫情况，自动补满之前所有状态
                        $sup = GiveModel::$sup;
                        if(!empty($sup[$user['group']]) && $give['status']<$sup[$user['group']]){
                            $sup_status = $sup[$user['group']];//需要补充到的状态
                            $status_flow_update = GiveModel::giveToStatus4($user,$status_flow,abs($give['status']),$sup_status,$give);

                            $give['status'] = $status_flow_update['status'];
                            $status_flow = $status_flow_update['status_flow'];

                            unset($status_flow_update['status']);
                            unset($status_flow_update['status_flow']);
                        }

                        if($give['give_status']<0 && abs($give['give_status']) == $role[$user['group']]['status'][0]){
                            $status = abs($give['status']);
                            $status_flow_update['quality_status'] = 2;//质检，已返修
                            $field_time = "status{$status}_time";
                        }
                        else {
                            $status = $give['status']+1;
                            $status = GiveModel::roleMill($user,$status,$give['is_process']);
                            $field_time = "status{$status}_time";

                            if(!strpos($status_flow,"_{$status}|") !== false){
                                if($status_flow)$status_flow .= ",";
                                $status_flow .= "_{$status}|{$uid}_";
                            }
                            else $time = 0;
                        }
                        if($give['give_status']<0)$time = 0;

                        // 验证权限
                        $msg = GiveModel::role($user,$status);
                        //验证该产品是否已取消生产
                        if($give['quality_status'] == -3)$msg = '该产品已取消生产';
                        //单独验证复合部权限
                        if(empty($give['is_process']) && $user['group'] == 10)$msg = '该订单无[复合]流程';
                        //单独验证发货部是否禁止发货
                        if($give['address_status'] < 0 && $user['group'] == 8)$msg = '该产品禁止发货';

                        //发货日志
                        if($user['group'] == 8)file_put_contents('扫码发货.log',date('Y-m-d H:i:s',$_log_time)."  档案号：{$give['archives_sn']}   编号：{$give['give_sn']}   扫码编号：{$v}\r\n".json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

                        //匹配批次
                        if(empty($msg) && $archives_sn && strpos($archives_sn,$give['archives_sn']) === false){
                            $msg = '批次不匹配';
                        }

                        //匹配喷涂颜色
                        if(empty($msg) && $color){
                            $give_color = Db::name('mill_order_archives')->where(['id'=>$give['archives_id']])->value('color');
                            if($color != $give_color)$msg = '颜色不匹配';
                        }

                        if(empty($msg) && !empty(GiveModel::$give_status[$status])){
                            $save = [
                                'status'                =>  $status,
                                'status_flow'           =>  $status_flow,
                                //'quality_flow_group'    =>  $group,
                                //$field_time             =>  $time,
                            ];
                            if(!empty($time))$save[$field_time] = $time;
                            if(!empty($status_flow_update))$save = array_merge($save,$status_flow_update);
                            //发货状态，绑定车牌ID
                            $address_status = GiveModel::$role[8]['status'][0];
                            if($field_time == "status{$address_status}_time" && !empty($car_id)){
                                //如果发货单号为空，则获取最近一个发货单号
                                $give['car_id'] = $car_id;
                                $address_sn = trim($address_sn);
                                if(empty($address_sn))$address_sn = AddressModel::lastAddressSn($uid,$give);
                                $save['car_id'] = $car_id;
                                $save['address_sn'] = $address_sn;
                            }
                            if(isset($give["status{$status}_sub"])){
                                $save = GiveModel::role_sub($user,$save,$give["status{$status}_sub"],$give['status']);
                            }

                            $give_where = ['id'=>$give['id']];
                            if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){
                                //检查更新产品主体状态
                                ArchivesModel::checkStatus($give['archives_id'],$status);
                            }
                        }

                        $give = Db::name('mill_order_archives_give')
                            ->alias('g')
                            ->field("a.*,o.batch,o.engineering,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
                            ->leftJoin('mill_order o','o.id=g.order_id')
                            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                            ->where(['g.id'=>$give['id']])
                            ->find();
                    }
                    else{
                        if(empty($msg))$msg = '该产品不存在';
                        $give['give_sn'] = $v;

                    }

                    if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                    //1：成功 0：失败
                    $give['status_code'] = empty($msg)?1:0;
                    $give['nickname'] = $user['nickname'];
                    $give['group_name'] = $user['group_name'];
                    //提示状态
                    $give['code_str'] = '该产品不存在';
                    if(isset($give['give_status']))$give['code_str'] = GiveModel::$give_status[$give['give_status']];

                    $give['status_str'] = $msg?$msg:'已上传';

                    $give['time_str'] = date('Y.m.d H:i');

                    $data_list[] = $give;

                    $_log_str .= "产品编号：{$give['give_sn']}  状态：{$give['status_str']}";
                }

                //file_put_contents('扫码reust.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".$_log_str."\r\n\r\n",FILE_APPEND);

                success('操作成功',$data_list);
            }
            errors('操作失败');
        }

        errors('操作异常');
    }
    /**
     * 分配发货单号
     */
    public function addressSn(){

        success('操作成功',['address_sn'=>GiveModel::getAddressSn()]);
    }
    /**
     * 确认发货
     * @return mixed
     */
    public function carGive()
    {

        //发货状态
        $status = GiveModel::$role[8]['status'][0];
        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            if (!isset($data['address_sn']))$data['address_sn'] = '';
            if (!isset($data['give_sn']))$data['give_sn'] = '';
            if (!isset($data['car_id']))$data['car_id'] = '';

            $address_sn_s = unique($data['address_sn']);

            //按批次分组
            $where = [
                ['address_sn','in',$address_sn_s],
                ['status','=',$status],
                ['address_status','=',0],

            ];
            $archives_ids = '';
            $give_list = Db::name('mill_order_archives_give')
                ->field('address_sn,order_pid,archives_sn,GROUP_CONCAT(id) as give_ids,GROUP_CONCAT(DISTINCT archives_id) as archives_ids')
                ->where($where)
                ->group('address_sn,order_id')
                ->select();

            $user = $this->member;

            $data_list = [];
            if(!empty($give_list)){

                $time = time();

                foreach ($give_list as $v){

                    $archives_ids .= ",{$v['archives_ids']}";
                    //分配发货单号
                    if(strpos($address_sn_s,$v['address_sn']) !== false){
                        $address_sn = $v['address_sn'];
                        $address_sn_s = str_replace($v['address_sn'],"",$address_sn_s);
                    }
                    else $address_sn = GiveModel::getAddressSn($time);

                    if(!empty($v['give_ids'])){
                        // 验证权限
                        $msg = GiveModel::role($user,$status);

                        if(empty($msg) && !empty(GiveModel::$give_status[$status])){
                            $save = [
                                'address_status'        =>  1,
                                'address_date'          =>  date('Y-m-d',$time),
                                'address_time'          =>  $time,
                                'address_sn'            =>  $address_sn,
                            ];

                            $give_where = [['id','in',$v['give_ids']]];

                            Db::name('mill_order_archives_give')->where($give_where)->update($save);
                        }

                    }
                    else{
                        $msg = '该产品已确认发货';
                        //$give['give_sn'] = $v;

                    }

                    //1：成功 0：失败
                    $give['status_code'] = empty($msg)?1:0;
                    $give['nickname'] = $user['nickname'];
                    $give['group_name'] = $user['group_name'];
                    //提示状态
                    $give['code_str'] = '';
                    $give['status_str'] = $msg?$msg:'已上传';
                    $give['time_str'] = date('Y.m.d H:i');

                    $data_list[] = $give;
                }

                //检查更新产品主体状态
                if(!empty($archives_ids)){
                    $archives_ids = explode(',',trim($archives_ids,','));
                    foreach ($archives_ids as $archives_id){
                        ArchivesModel::checkStatus($archives_id,$status);
                    }

                }
                success('操作成功',[]);
            }
            success('后台已确认装车',[]);
        }

        errors('操作异常');
    }
    /**
     * 扫码质检产品状态
     * @return mixed
     */
    public function qualityStatus(){

        $status_list = GiveModel::$give_status_search;
        unset($status_list[0]);

        $list = [];
        foreach ($status_list as $k=>$v){
            $list[] = [
                'id'        =>  $k,
                'title'     =>  $v,
            ];
        }

        success('', array('list' => $list, 'pagesize' => 999, 'total' => 999, 'pindex' => 999, 'total_pages' => 1));
    }
    /**
     * 扫码质检产品
     * @return mixed
     */
    public function quality(){
        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            if(empty($data['status']))$data['status'] = 0;

            if(empty($data['give_status']) && $data['status'] < 0)errors([],['status_code'=>0,'status_str'=>'请选择责任环节']);

            $user = $this->member;

            //质检
            $re = GiveModel::quality($user,$data);

            if($re){
                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field("a.*,o.batch,o.engineering,g.give_sn,g.archives_sn,g.quality_status,g.counter,g.status as give_status,concat(g.counter,'/',a.number) as number_str")
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where(['g.give_sn'=>$data['give_sn']])
                    ->find();

                $give['nickname'] = $user['nickname'];
                $give['group_name'] = $user['group_name'];

                //提示状态
                $give['code_str'] = GiveModel::$give_status[abs($give['give_status'])].GiveModel::$quality_status[$give['quality_status']];
                if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                $give['status_code'] = 1;
                $give['status_str'] = '已上传';
                $give['time_str'] = date('Y.m.d H:i');

                success('操作成功',$give);
            }
            errors($re,['status_code'=>0,'status_str'=>$re]);
        }

        errors('操作异常');
    }
    /**
     * 历史记录
     */
    public function giveList(){
        $user = $this->member;

        $sub_status = input('sub_status');
        $pindex = max(1, intval(input('page',1)));
        $psize = 30;

        $role_status = GiveModel::$role[$user['group']];

        $where = [];
        $order = '';

        //质检部
        if(isset($role_status['quality'])){

            $where[] = ['g.quality_uid','=',$user['uid']];
            $order .= 'g.quality_time desc';
        }
        //其他部门
        else{
            if(!empty($sub_status) && isset($role_status['status'][0]))$where[] = ["g.status{$role_status['status'][0]}_sub",'=',1];
            $where[] = ['g.status_flow','like',"%|{$user['uid']}\\_%"];
            //排序
            foreach ($role_status as $field=>$val){
                if(is_array($val)){
                    foreach ($val as $v){
                        if($field == 'color' || $field == 'sub')continue;
                        if($v === true)$v = '';
                        $order .= "g.{$field}{$v}_time desc,";
                    }
                }
            }
        }

        $order = trim($order,',');
        /*$list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("a.*,o.batch,o.engineering,g.status as give_status,g.id as give_id,g.give_sn,g.archives_sn,g.status_flow,g.status1_time,g.status2_time,g.status3_time,g.status4_time,g.quality_time,g.quality_status,g.counter,concat(g.counter,'/',a.number) as number_str")
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($where)
            ->order($order)
            ->limit((($pindex-1)*$psize),$psize)
            ->select();*/
        $order_ids = Db::name('mill_order_archives_give')
            ->alias('g')
            ->where($where)
            ->order($order)
            ->limit((($pindex-1)*$psize),$psize)
            ->column("DISTINCT g.order_id");
        $list = [];

        if(!empty($order_ids)){
            foreach ($order_ids as $order_id){

                $give_where = $where;
                $give_where[] = ['g.order_id','=',$order_id];
                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field("o.*,g.status_flow,g.status1_time,g.status2_time,g.status3_time,g.status4_time,g.quality_time,g.quality_status")
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->where($give_where)
                    ->order($order)
                    ->find();
                $give['order_sn'] = $give['archives_sn'];

                //质检部
                if(isset($role_status['quality'])){

                    $field_time = "quality_time";
                }
                //其他部门
                else{

                    $give_status = GiveModel::giveStatusOrUid($give['status_flow'],$user['uid']);

                    $field_time = "status".abs($give_status)."_time";
                }

                $give['time_str'] = date('Y.m.d H:i',$give[$field_time]);

                //总数量
                $give['archives_sum'] = Db::name('mill_order_archives')
                    ->where(['order_id'=>$order_id])
                    ->sum("number");
                //已扫总数量
                $give['status_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->where("g.order_id = {$order_id} and g.status != 0")
                    ->count("DISTINCT g.id");
                //当前账号已扫数量
                $give['number'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->where($give_where)
                    ->count("DISTINCT g.id");

                $list[] = $give;
            }
        }

        $total = Db::name('mill_order_archives_give')
            ->alias('g')
            ->where($where)
            ->order($order)
            ->count("DISTINCT g.order_id");

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 车牌列表
     */
    public function carList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $where = ['status'=>1];
        $order = 'id desc';

        $list = Db::name('mill_car')
            ->where($where)
            ->order($order)
            //->limit((($pindex-1)*$psize),$psize)
            ->select();

        $total = Db::name('mill_car')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 批次列表
     */
    public function batchList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $archives_sn = input('archives_sn');
        $archives_sn = str_replace('，',',',strtoupper($archives_sn));
        $archives_sn_arr = explode(',',$archives_sn);
        $where_sn = '';
        if(!empty($archives_sn_arr) && !empty($archives_sn)){
            foreach ($archives_sn_arr as $sn){
                if(!empty($where_sn))$where_sn .= ' OR ';
                $where_sn .= " o.archives_sn like '%{$sn}%'";
            }
        }

        $where = [['o.status','=',1],['g.status','<',4]];
        $order = 'o.status_time desc,o.id desc';

        $list = Db::name('mill_order')
            ->field("o.id,o.archives_sn,o.batch,concat(o.archives_sn,'/',o.batch) as batch_str")
            ->alias('o')
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->where($where)
            ->where($where_sn)
            ->group('o.id')
            ->order($order)
            //->limit((($pindex-1)*$psize),$psize)
            ->select();

        $total = Db::name('mill_order')
            ->alias('o')
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 颜色列表
     */
    public function colorList(){
        $user = $this->member;

        $archives_sn = input('archives_sn');
        if(empty($archives_sn))errors('请选择批次');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $where = [['archives_sn','in',$archives_sn]];
        $order = 'id asc';

        $list = Db::name('mill_order_archives')
            ->field("distinct color")
            ->where($where)
            ->order($order)
            //->limit((($pindex-1)*$psize),$psize)
            ->select();

        $total = Db::name('mill_order')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 产品列表
     */
    public function archivesGiveList(){
        $user = $this->member;

        $archives_sn = input('archives_sn');
        $give_sn = input('give_sn');
        if(empty($archives_sn))errors('请选择批次');
        if(empty($give_sn))errors('请输入产品编号');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $list = [];

        $give_sn = explode(',',$give_sn);
        foreach ($give_sn as $k=>$v){

            $where[] = ['g.give_sn','=',$v];

            //判断产品编号是否完整
            if(strpos($v,'-') === false){

                $where = [
                    ['g.give_sn','like',"%-{$v}"],
                ];
            }
            $where[] = ['g.archives_sn','=',$archives_sn];

            $give = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field("a.*,o.batch,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->where($where)
                ->find();

            if($give){
                if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                $give['status_str'] = GiveModel::$give_status[$give['give_status']];

                $list[] = $give;
            }

        }

        $total = 99999;

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 批次发货情况统计
     */
    public function carBatchStat(){
    $user = $this->member;

    $archives_sn = input('archives_sn');
    $color = input('color');
    $car_id = input('car_id');
    $address_sn = input('address_sn');
    if(empty($archives_sn))errors('请选择批次');
    $pindex = max(1, intval(input('page',1)));
    $psize = 1;

    $role_status = GiveModel::$role[$user['group']];

    $archives_sn_arr = explode(',',$archives_sn);
    $list = [];
    foreach ($archives_sn_arr as $sn){

        $order = Db::name('mill_order')->where([['archives_sn','=',$sn]])->find();

        $archives_sn_str = mb_substr($order['archives_sn'],strpos($order['archives_sn'],'-')+1);
        $stat['archives_sn'] = "{$archives_sn_str}";
        //总数量
        $stat_where = [['g.order_id','=',$order['id']],['g.quality_status','>',-2]];
        if($color)$stat_where[] = ['a.color','=',$color];
        $stat['give_sum'] = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($stat_where)
            ->count('g.id');
        //echo Db::name('mill_order')->getLastSql();exit;

        if(!empty($role_status['status'][0])){
            $status = $role_status['status'][0];
            $status_str = GiveModel::$give_status[$status];
            //已扫码数量
            $stat_where = [
                ['g.order_id','=',$order['id']],
                ['g.status','>=',$status]
            ];
            //喷涂
            if($color){
                //已喷涂数量
                $stat_where[] = ['a.color','=',$color];
                $stat['ok_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($stat_where)
                    ->count();
            }
            //开料，钣金，发货
            else $stat['ok_sum'] = Db::name('mill_order_archives_give')->alias('g')->where($stat_where)->count();

            $stat['status_str'] = "总数:{$stat['give_sum']}/已{$status_str}:{$stat['ok_sum']}/未{$status_str}:".($stat['give_sum']-$stat['ok_sum']);

            //扫码人情况
            if($user['group'] == 8){
                $stat_where[] = ['g.status_flow','like',"%\\_{$status}|{$user['uid']}\\_%"];
                if($car_id)$stat_where[] = ['g.car_id','=',$car_id];
                if($address_sn)$stat_where[] = ['g.address_sn','=',$address_sn];

                //备注
                $note = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$order['id']])->value('note');
                if($note)$note = "（{$note}）";

                $stat['user_ok_sum'] = Db::name('mill_order_archives_give')->alias('g')->where($stat_where)->count();

                $stat['status_str'] = "当车已扫:{$stat['user_ok_sum']}/未{$status_str}:".($stat['give_sum']-$stat['ok_sum']).$note;
            }
        }

        $list[] = $stat;
    }

    $total = count($archives_sn_arr);

    success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
}
    /**
     * 新增车牌号
     */
    public function addCar(){

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            $rule = [
                'plate_number|车牌号' => 'require',
            ];
            if(($message =$this->validate($data,$rule)) !== true)errors([],$message);

            //函数:SBC_DBC  中文标点转英文标点
            //函数:replaceSpecialChar  去除所有标点字符包括空格
            //函数:strtoupper  转大写
            $data['plate_number'] = filterStr($data['plate_number']);
            $update = [
                'plate_number'  =>  $data['plate_number'],
            ];
            $count = Db::name('mill_car')->where($update)->count();
            if($count > 0)errors('该车牌号已存在');
            $re = Db::name('mill_car')->insert($update);

            if(!empty($re))success('提交成功');
            errors('提交失败,请重试');

        }

    }
    /**
     * 确认产品进度
     * @return mixed
     */
    public function subGive()
    {

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $archives_sn_s = unique($data['archives_sn']);

            $user = $this->member;
            $role_status = GiveModel::$role[$user['group']]['status'][0];

            //按批次分组
            $where = [
                ['archives_sn','in',$archives_sn_s],
                ["status{$role_status}_sub",'=',1],
                ['status_flow','like',"%\\_{$role_status}|{$user['uid']}\\_%"],

            ];

            $save = [
                'status'                             =>  $role_status,
                "status{$role_status}_sub"           =>  2,
                "status{$role_status}_time"          =>  time(),
            ];

            //Db::name('mill_order_archives_give')->where($where)->select();
            Db::name('mill_order_archives_give')->where($where)->update($save);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
}
